package com.zb.kc.order.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.kc.commonutils.JwtUtils;
import com.zb.kc.commonutils.R;
import com.zb.kc.commonutils.ResultCode;
import com.zb.kc.order.entity.Order;
import com.zb.kc.order.service.OrderService;
import com.zb.kc.servicebase.exceptionhandler.KgcException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author wanggen
 * @since 2020-04-23
 */
@RestController
@RequestMapping("/eduorder/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "生成订单")
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String memerId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memerId)) {
            throw new KgcException(ResultCode.UNLOGINERR);
        }
        String orderNo = orderService.createOrders(courseId, memerId);
        return R.ok().data(orderNo);
    }

    @ApiOperation(value = "根据订单编号查询订单信息")
    @GetMapping("{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo) {
        Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        return R.ok().data(order);
    }

    @ApiOperation(value = "根据课程id和用户id查询订单状态")
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId, @PathVariable String memberId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("status", 1);
        int count = orderService.count(queryWrapper);
        return count > 0;
    }
}
